/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import daos.exceptions.PreexistingEntityException;
import daos.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entidades.Competencia;
import entidades.EspacioDeportivo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author usuario
 */
public class EspacioDeportivoJpaController implements Serializable {

    public EspacioDeportivoJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(EspacioDeportivo espacioDeportivo) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (espacioDeportivo.getCompetenciaCollection() == null) {
            espacioDeportivo.setCompetenciaCollection(new ArrayList<Competencia>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Competencia> attachedCompetenciaCollection = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionCompetenciaToAttach : espacioDeportivo.getCompetenciaCollection()) {
                competenciaCollectionCompetenciaToAttach = em.getReference(competenciaCollectionCompetenciaToAttach.getClass(), competenciaCollectionCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollection.add(competenciaCollectionCompetenciaToAttach);
            }
            espacioDeportivo.setCompetenciaCollection(attachedCompetenciaCollection);
            em.persist(espacioDeportivo);
            for (Competencia competenciaCollectionCompetencia : espacioDeportivo.getCompetenciaCollection()) {
                EspacioDeportivo oldEspacioDeportivoOfCompetenciaCollectionCompetencia = competenciaCollectionCompetencia.getEspacioDeportivo();
                competenciaCollectionCompetencia.setEspacioDeportivo(espacioDeportivo);
                competenciaCollectionCompetencia = em.merge(competenciaCollectionCompetencia);
                if (oldEspacioDeportivoOfCompetenciaCollectionCompetencia != null) {
                    oldEspacioDeportivoOfCompetenciaCollectionCompetencia.getCompetenciaCollection().remove(competenciaCollectionCompetencia);
                    oldEspacioDeportivoOfCompetenciaCollectionCompetencia = em.merge(oldEspacioDeportivoOfCompetenciaCollectionCompetencia);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findEspacioDeportivo(espacioDeportivo.getIdEspacioDeportivo()) != null) {
                throw new PreexistingEntityException("EspacioDeportivo " + espacioDeportivo + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(EspacioDeportivo espacioDeportivo) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            EspacioDeportivo persistentEspacioDeportivo = em.find(EspacioDeportivo.class, espacioDeportivo.getIdEspacioDeportivo());
            Collection<Competencia> competenciaCollectionOld = persistentEspacioDeportivo.getCompetenciaCollection();
            Collection<Competencia> competenciaCollectionNew = espacioDeportivo.getCompetenciaCollection();
            List<String> illegalOrphanMessages = null;
            for (Competencia competenciaCollectionOldCompetencia : competenciaCollectionOld) {
                if (!competenciaCollectionNew.contains(competenciaCollectionOldCompetencia)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Competencia " + competenciaCollectionOldCompetencia + " since its espacioDeportivo field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Competencia> attachedCompetenciaCollectionNew = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionNewCompetenciaToAttach : competenciaCollectionNew) {
                competenciaCollectionNewCompetenciaToAttach = em.getReference(competenciaCollectionNewCompetenciaToAttach.getClass(), competenciaCollectionNewCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollectionNew.add(competenciaCollectionNewCompetenciaToAttach);
            }
            competenciaCollectionNew = attachedCompetenciaCollectionNew;
            espacioDeportivo.setCompetenciaCollection(competenciaCollectionNew);
            espacioDeportivo = em.merge(espacioDeportivo);
            for (Competencia competenciaCollectionNewCompetencia : competenciaCollectionNew) {
                if (!competenciaCollectionOld.contains(competenciaCollectionNewCompetencia)) {
                    EspacioDeportivo oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia = competenciaCollectionNewCompetencia.getEspacioDeportivo();
                    competenciaCollectionNewCompetencia.setEspacioDeportivo(espacioDeportivo);
                    competenciaCollectionNewCompetencia = em.merge(competenciaCollectionNewCompetencia);
                    if (oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia != null && !oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia.equals(espacioDeportivo)) {
                        oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia.getCompetenciaCollection().remove(competenciaCollectionNewCompetencia);
                        oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia = em.merge(oldEspacioDeportivoOfCompetenciaCollectionNewCompetencia);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = espacioDeportivo.getIdEspacioDeportivo();
                if (findEspacioDeportivo(id) == null) {
                    throw new NonexistentEntityException("The espacioDeportivo with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            EspacioDeportivo espacioDeportivo;
            try {
                espacioDeportivo = em.getReference(EspacioDeportivo.class, id);
                espacioDeportivo.getIdEspacioDeportivo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The espacioDeportivo with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Competencia> competenciaCollectionOrphanCheck = espacioDeportivo.getCompetenciaCollection();
            for (Competencia competenciaCollectionOrphanCheckCompetencia : competenciaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This EspacioDeportivo (" + espacioDeportivo + ") cannot be destroyed since the Competencia " + competenciaCollectionOrphanCheckCompetencia + " in its competenciaCollection field has a non-nullable espacioDeportivo field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(espacioDeportivo);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<EspacioDeportivo> findEspacioDeportivoEntities() {
        return findEspacioDeportivoEntities(true, -1, -1);
    }

    public List<EspacioDeportivo> findEspacioDeportivoEntities(int maxResults, int firstResult) {
        return findEspacioDeportivoEntities(false, maxResults, firstResult);
    }

    private List<EspacioDeportivo> findEspacioDeportivoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(EspacioDeportivo.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public EspacioDeportivo findEspacioDeportivo(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(EspacioDeportivo.class, id);
        } finally {
            em.close();
        }
    }

    public int getEspacioDeportivoCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<EspacioDeportivo> rt = cq.from(EspacioDeportivo.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
